'use strict';

var mongoose = require('mongoose');
var modelPlugin = require("../model.plugin");
var Schema = mongoose.Schema;
var ObjectId  = Schema.ObjectId;

var roleSchema = new Schema({
  name: {type: String, required: true},
  priority: {type: Number},
  feature: {type: String, required: true, unique: true},
  description: {type: String},
  //{0: disable, 1: used, 2: ...}
  state: {type: Number, enum:[0, 1, 2], default: 1},
  defaultRole: {type: Boolean, enum:[true, false], default: false},
  userSize: {type: Number},

  createdAt: {type: Date, default: Date.now},
  createdBy: {type: ObjectId, ref: 'User'},
  updatedAt: {type: Date, default: Date.now},
  updatedBy: {type: ObjectId, ref: 'User'},

  /*menuList: [{
    name: {type: String},
    feature: {type: String},
    menuType: {type: Number},
    state: {type: Number},
    sort: {type: Number},
    description: {type: String},

    operatorList: [{
      name: {type: String},
      action: {type: String},
      state: {type: Number}
    }]
  }]*/
  purview: [{
    menu: {type: ObjectId, ref: 'Menu'},
    operatorList: [{type: ObjectId, ref: 'Operator'}]
  }]
});

roleSchema.virtual('operators').get(function() {
  var operators = [];
  if (this.purview) {
    for (var i = 0; i < this.purview.length; i ++) {
      if (this.purview[i].operatorList) {
        var tmp = '';
        for (var j = 0; j < this.purview[i].operatorList.length; j ++) {
          if (tmp === '') {
            tmp += this.purview[i].operatorList[j].action + '|';
          } else {
            tmp += this.purview[i].operatorList[j].action;
          }
        }
        operators.push(tmp);
      }
    }
  }
  return operators;
});

roleSchema.plugin(modelPlugin);
roleSchema.index({feature: 1});

mongoose.model('Role', roleSchema);
